﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Mvc;
using CubicFWNet.Mvc.Models;
using CubicFWNet.Application.SystemManager;
using CubicFWNet.Common;
using CubicFWNet.Data.Models;
using CubicFWNet.Data.ViewModal;
using PagedList;

namespace CubicFWNet.Mvc.Controllers
{
    public class OrderController : ControllerBase
    {
        private OrderApp _orderApp;
        private CustomerApp _customerApp;
        private CustomerProductApp _customerProductApp;
        private ProductApp _productApp;
        private OrderProductApp _orderProductApp;
        private InvoiceApp _invoiceApp;
        private StorageTableApp _storageTableApp;
        private WorksheetApp _worksheetApp;
        private PurchaseApp _purchaseApp;
        private OperateRecordApp _operateRecordApp;
        private InventoryUerApp _inventoryUerApp;
        private CreateNewNumberApp _createNewNumberApp;
        private UserApp _userApp;
        private InventoryChangeApplyApp _inventoryChangeApplyApp;

        private Guid roleID = new Guid("4cf6a365-e372-42ce-bd05-ceec18b294a4");

        public OrderController()
        {
            _orderApp = new OrderApp();
            _customerApp = new CustomerApp();
            _productApp = new ProductApp();
            _purchaseApp = new PurchaseApp();
            _orderProductApp = new OrderProductApp();
            _invoiceApp = new InvoiceApp();
            _customerProductApp = new CustomerProductApp();
            _storageTableApp = new StorageTableApp();
            _worksheetApp = new WorksheetApp();
            _operateRecordApp = new OperateRecordApp();
            _inventoryUerApp = new InventoryUerApp();
            _createNewNumberApp = new CreateNewNumberApp();
            _userApp = new UserApp();
            _inventoryChangeApplyApp = new InventoryChangeApplyApp();
        }

        public ViewResult Index()
        {
            return View();
        }

        /// <summary>
        /// 查询产品申请
        /// </summary>
        /// <returns></returns>
        public ActionResult ApplyList(int page = 1, string start = "", string end = "", string name = "", string number = "")
        {
            DateTime _start = Convert.ToDateTime("2017-1-1");
            DateTime _end = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

            if (start != "")
            {
                _start = Convert.ToDateTime(start);
            }
            if (end != "")
            {
                _end = Convert.ToDateTime(end);
            }

            ViewBag.Start = _start.ToString("yyyy-MM-dd");
            ViewBag.End = _end.ToString("yyyy-MM-dd");
            ViewBag.Name = name;
            ViewBag.Number = number;

            ViewBag.SalerList = _customerApp.GetUserList(roleID);
            string saler = operatorModel.UserId.ToString();
            if (operatorModel.UserName == "admin")
            {
                saler = "";
            }
            IPagedList<OrderInfo> orderList = _orderApp.GetList(_start, _end.AddDays(1), 2, 0, name, saler, number).ToPagedList(page, 10);
            return View(orderList);
        }

        /// <summary>
        /// 提交最终价
        /// </summary>
        /// <returns></returns>
        public ActionResult ApplyPrice(int page = 1, string start = "", string end = "", string name = "", string number = "")
        {
            DateTime _start = Convert.ToDateTime("2017-1-1");
            DateTime _end = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

            if (start != "")
            {
                _start = Convert.ToDateTime(start);
            }
            if (end != "")
            {
                _end = Convert.ToDateTime(end);
            }

            ViewBag.Start = _start.ToString("yyyy-MM-dd");
            ViewBag.End = _end.ToString("yyyy-MM-dd");
            ViewBag.Name = name;
            ViewBag.Number = number;

            ViewBag.SalerList = _customerApp.GetUserList(roleID);
            string saler = operatorModel.UserId.ToString();
            if (operatorModel.UserName == "admin" || operatorModel.UserName=="xiaoshouzongjian")
            {
                saler = "";
            }
            IPagedList<OrderInfo> orderList = _orderApp.GetList(_start, _end.AddDays(1), 2, 501, name, saler, number).ToPagedList(page, 10);
            return View(orderList);
        }
        

        /// <summary>
        /// 确认下单列表
        /// </summary>
        /// <returns></returns>
        public ActionResult ConfirmOrders(int page = 1, string start = "", string end = "", string name = "", string number = "")
        {
            DateTime _start = Convert.ToDateTime("2017-1-1");
            DateTime _end = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

            if (start != "")
            {
                _start = Convert.ToDateTime(start);
            }
            if (end != "")
            {
                _end = Convert.ToDateTime(end);
            }

            ViewBag.Start = _start.ToString("yyyy-MM-dd");
            ViewBag.End = _end.ToString("yyyy-MM-dd");
            ViewBag.Name = name;
            ViewBag.Number = number;

            ViewBag.SalerList = _customerApp.GetUserList(roleID);
            string saler = operatorModel.UserId.ToString();
            if (operatorModel.UserName == "admin")
            {
                saler = "";
            }
            IPagedList<OrderInfo> orderList = _orderApp.GetList(_start, _end.AddDays(1), 2, 6, name, saler, number).ToPagedList(page, 10);
            return View(orderList);
        }

        /// <summary>
        /// 订单列表【销售员查看自己订单及操作】
        /// </summary>
        /// <param name="page"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="name"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        public ActionResult OrderList(int page = 1, string start = "", string end = "", string name = "", string number = "")
        {
            DateTime _start = Convert.ToDateTime("2017-1-1");
            DateTime _end = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
            if (start != "")
            {
                _start = Convert.ToDateTime(start);
            }
            if (end != "")
            {
                _end = Convert.ToDateTime(end);
            }

            ViewBag.Start = _start.ToString("yyyy-MM-dd");
            ViewBag.End = _end.ToString("yyyy-MM-dd");
            ViewBag.Name = name;
            ViewBag.Number = number;

            ViewBag.SalerList = _customerApp.GetUserList(roleID);
            string saler = operatorModel.UserId.ToString();
            if (operatorModel.UserName == "admin")
            {
                saler = "";
            }
            IPagedList<OrderInfo> orderList = _orderApp.GetList(_start, _end.AddDays(1), 3, 0, name, saler, number).ToPagedList(page, 10);
            return View(orderList);
        }


        /// <summary>
        /// 查询订单列表【只能查看】
        /// </summary>
        /// <param name="page"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="name"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        public ActionResult OrderSel(int page = 1, string start = "", string end = "", string name = "", string number = "")
        {
            DateTime _start = Convert.ToDateTime("2017-1-1");
            DateTime _end = DateTime.Now.AddDays(1);
            if (start != "")
            {
                _start = Convert.ToDateTime(start);
            }
            if (end != "")
            {
                _end = Convert.ToDateTime(end);
            }

            ViewBag.Start = _start.ToString("yyyy-MM-dd");
            ViewBag.End = _end.ToString("yyyy-MM-dd");
            ViewBag.Name = name;
            ViewBag.Number = number;

            ViewBag.SalerList = _customerApp.GetUserList(roleID);
            IPagedList<OrderInfo> orderList = _orderApp.GetList(_start, _end, 3, 0, name, "", number).ToPagedList(page, 10);
            return View(orderList);
        }

        /// <summary>
        /// 订单信息
        /// </summary>
        /// <returns></returns>
        public ActionResult OrderInfo()
        {
            Guid oid = new Guid(Request.QueryString["OID"]);
            OrderInfo order = _orderApp.GetFullInfo(oid);
            List<ProductView> lsPro = _orderProductApp.GetListByOrderID(oid).ToList();
            ViewBag.Order = order;
            ViewBag.ProList = lsPro;
            return View();
        }

        /// <summary>
        /// 提交产品申请
        /// </summary>
        /// <returns></returns>
        public ActionResult ApplyAdd()
        {
            string cusID = Request.QueryString["CID"];
            List<ProductView> proList = new List<ProductView>();
            Customer cus = new Customer();
            if (cusID != null)
            {
                try
                {
                    cus = _customerApp.GetInfo(new Guid(cusID));
                    if (cus != null)
                    {
                        proList = _customerProductApp.GetCustomerProList(cus.Id);
                    }
                }
                catch
                { }
            }
            ViewBag.ProductList = proList;
            ViewBag.Customer = cus;
            Guid salerID = operatorModel.UserId;
            if (operatorModel.UserName == "admin")
            {
                salerID = new Guid();
            }
            ViewBag.CustomerList = _customerApp.GetList("", salerID, 1);
            ViewBag.SalerList = _customerApp.GetUserList(roleID);
            ViewBag.RealName = operatorModel.FamilyName;
            return View();
        }

        ///// <summary>
        ///// 提交产品申请
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost]
        //public ActionResult ApplyAdd(FormCollection fc)
        //{
        //    Order order = new Order();
        //    order.Id = Guid.NewGuid();
        //    order.CustomeId = new Guid(fc["CusID"]);
        //    //order.UserId = new Guid(fc["Saler"]);
        //    order.UserId = operatorModel.UserId;
        //    order.Channel = fc["Channel"];
        //    order.Number = fc["Number"];
        //    order.Delivery = fc["Delivery"];
        //    order.Memo = fc["Memo"];
        //    order.InitPrice = 0;
        //    order.FinalPrice = 0;
        //    order.Status = 2;
        //    order.Stage = 2;
        //    order.CreateTime = DateTime.Now;
        //    order.CreatorId = operatorModel.UserId;
        //    order.CreatorName = operatorModel.FamilyName;

        //    string proList = fc["ProData"];
        //    JavaScriptSerializer js = new JavaScriptSerializer();
        //    List<ModelOP> ls = js.Deserialize<List<ModelOP>>(proList);

        //    //订单对应产品信息&工艺信息
        //    List<OrderProduct> opList = new List<OrderProduct>();
        //    List<Technology> tcList = new List<Technology>();
        //    foreach (ModelOP obj in ls)
        //    {
        //        OrderProduct op = new OrderProduct();

        //        op.Id = Guid.NewGuid();
        //        op.ProductId = obj.PID;
        //        op.OrderId = order.Id;
        //        op.Amount = obj.Amount;
        //        op.PurchaseId = new Guid();
        //        op.WorksheetId = new Guid();
        //        op.Price = obj.Price;
        //        op.PriceTime = DateTime.Now;

        //        opList.Add(op);

        //        Technology tc = new Technology();
        //        tc.Id = Guid.NewGuid();
        //        tc.ApplyTime = DateTime.Now;
        //        tc.CreateTime = DateTime.Now;
        //        tc.CreatorID = new Guid();
        //        tc.OrderProductId = op.Id;
        //        tc.UserId = operatorModel.UserId;
        //        tc.Status = -1;
        //        tc.Number = operatorModel.ShortName + "-" + GenerateId.GenerateOrderNumber();

        //        tcList.Add(tc);
        //    }
        //    //添加对应产品
        //    int res1 = _orderProductApp.Add(opList);

        //    if (res1 > 0)
        //    {
        //        //添加订单
        //        int res2 = _orderApp.Insert(order);
        //        if (res2 == 1)
        //        {
        //            //添加工艺                
        //            _orderProductApp.AddTechnology(tcList);
        //            return RedirectToAction("ApplyList", "Order");
        //        }
        //        else
        //        {
        //            ViewBag.Info = "抱歉，订单提交失败！";
        //        }
        //    }
        //    else
        //    {
        //        ViewBag.Info = "抱歉，订单提交失败！";
        //    }

        //    Guid salerID = operatorModel.UserId;
        //    if (operatorModel.UserName == "admin")
        //    {
        //        salerID = new Guid();
        //    }
        //    ViewBag.CustomerList = _customerApp.GetList("", salerID, 1);
        //    ViewBag.ProductList = _productApp.GetList(1, 1, "", "");
        //    ViewBag.SalerList = _customerApp.GetUserList(new Guid("4cf6a365-e372-42ce-bd05-ceec18b294a4"));
        //    ViewBag.RealName = operatorModel.FamilyName;
        //    return View();
        //}

        /// <summary>
        /// 获取客户产品关联信息
        /// </summary>
        /// <param name="CID"></param>
        /// <returns></returns>
        public JsonResult GetCusProduct(string CID)
        {
            Guid id = new Guid(CID);
            List<ProductView> ls = _customerProductApp.GetList(id);
            return Json(ls);
        }

        /// <summary>
        /// 确认产品价格
        /// </summary>
        /// <returns></returns>
        public ActionResult ConfirmPrice()
        {
            string str = Request.QueryString["OID"];
            OrderInfo order = new OrderInfo();
            List<ProductView> opList = new List<ProductView>();
            if (str != null)
            {
                Guid oID = new Guid(str);
                order = _orderApp.GetFullInfo(oID);
                if (order != null)
                {
                    opList = _orderProductApp.GetListByOrderID(oID).ToList();
                }
            }

            ViewBag.Order = order;
            ViewBag.OpList = opList;
            return View();
        }

        /// <summary>
        /// 提交价格申请
        /// </summary>
        /// <param name="fc"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ConfirmPrice(FormCollection fc)
        {
            Guid oID = new Guid(fc["OrderID"]);
            Order order = _orderApp.GetInfo(oID);

            string proList = fc["Data"];
            JavaScriptSerializer js = new JavaScriptSerializer();
            List<ModelProPrice> ls = js.Deserialize<List<ModelProPrice>>(proList);

            for (int i = 0; i < ls.Count; i++)
            {
                OrderProduct op = _orderProductApp.GetSingleOrderProduct(ls[i].ID);
                op.FinalPrice = ls[i].Price;
                op.PriceTime = DateTime.Now;
                _orderProductApp.Update(op);
            }

            order.Status = 502; //下一步，销售总监审核
            _orderApp.Update(order);
            return RedirectToAction("ApplyPrice", "Order");

        }

        /// <summary>
        /// 确认订单
        /// </summary>
        /// <returns></returns>
        public ActionResult ConfirmOrder()
        {
            string str = Request.QueryString["OID"];
            decimal price = 0;
            OrderInfo order = new OrderInfo();
            List<ProductView> opList = new List<ProductView>();

            if (str != null)
            {
                Guid oID = new Guid(str);
                order = _orderApp.GetFullInfo(oID);
                if (order != null)
                {
                    opList = _orderProductApp.GetListByOrderID(oID).ToList();
                }
            }

            DateTime start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            DateTime end = DateTime.Now.AddDays(1);
            int count = _orderApp.GetOrderCount(operatorModel.UserId, start, end);
            count += 1;
            string tmp = count.ToString();
            if (count < 10)
            {
                tmp = "00" + count;
            }
            else if (count < 100)
            {
                tmp = "0" + count;
            }

            ViewBag.Number = operatorModel.FamilyName + "-" + GenerateId.GenerateOrderNumberBack() + "-" + tmp;

            ViewBag.Price = price;
            ViewBag.Order = order;
            ViewBag.OpList = opList;
            return View();
        }

        /// <summary>
        /// 确认订单[提交数据]
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ConfirmOrder(FormCollection fc)
        {
            Guid oID = new Guid(fc["OrderID"]);
            Guid tmpID = Guid.NewGuid();
            Order order = _orderApp.GetInfo(oID);
            order.Channel = fc["Channel"];
            order.Number = fc["Number"];
            order.CusNumber = fc["CusNumber"];
            order.Delivery = fc["Delivery"];
            order.Memo = fc["Memo"];
            order.SendTime = fc["SendTime"];
            order.FinalPrice = order.InitPrice = Convert.ToDecimal(fc["Price"]);
            order.IsWork = Convert.ToInt32(fc["IsWork"]);

            order.Status = 8; //采购
            order.Stage = 3;
            order.CreateTime = DateTime.Now;
            order.SubmitTime = DateTime.Now;
            _orderApp.Update(order);
            List<OrderProduct> opList = _orderProductApp.GetOrderProductByOrder(oID).ToList();

            //订货数量
            string proList = fc["ProData"];
            JavaScriptSerializer js = new JavaScriptSerializer();
            List<ProTemp> ls = js.Deserialize<List<ProTemp>>(proList);

           //循环产品
            foreach (var obj in opList)
            {
                for (int i = 0; i < ls.Count; i++)
                {
                    if (ls[i].ProductID == obj.Id)
                    {
                        obj.Amount = ls[i].Amount;
                    }
                }
                //更新订货数量 
                tmpID = Guid.NewGuid();
                obj.PurchaseId = tmpID;
                _orderProductApp.Update(obj);


                //插入“生产分配”数据
                if (order.IsWork == 1)
                {
                    Purchase pur = new Purchase();
                    pur.Id = tmpID;
                    pur.Status = 1;
                    pur.Type = 1;
                    pur.Amount = obj.Amount;
                    pur.ApplyTime = DateTime.Now;
                    pur.ApplyId = operatorModel.UserId;
                    _purchaseApp.Add(pur);
                }

                //插入“转库存”申请
                else if (order.IsWork == 2)
                {
                    InventoryChangeApply ica = new InventoryChangeApply();
                    ica.Id = Guid.NewGuid();
                    ica.OrderId = order.Id;
                    ica.ProductId = obj.ProductId;
                    ica.ApplyAmount = obj.Amount;
                    ica.FinishAmount = 0;
                    ica.Status = -1;
                    ica.ApplyTime = DateTime.Now;
                    _inventoryChangeApplyApp.Add(ica);
                }



            }

            return RedirectToAction("ConfirmOrders", "Order");
        }

        /// <summary>
        /// 再次下单
        /// </summary>
        /// <returns></returns>
        public ActionResult AgainOrder()
        {
            Guid cID = new Guid();
            Customer cus = new Customer();
            string str = Request.QueryString["CID"];
            decimal price = 0;

            List<ProductView> cusProList = new List<ProductView>();
            if (str != null)
            {
                cID = new Guid(str);
                cus = _customerApp.GetInfo(cID);
                cusProList = _customerProductApp.GetCustomerOrderProductList(cID);
            }

            DateTime start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            DateTime end = DateTime.Now.AddDays(1);
            int count = _orderApp.GetOrderCount(operatorModel.UserId, start, end);
            count += 1;
            string tmp = count.ToString();
            if (count < 10)
            {
                tmp = "00" + count;
            }
            else if (count < 100)
            {
                tmp = "0" + count;
            }

            ViewBag.Number = operatorModel.FamilyName + "-" + GenerateId.GenerateOrderNumberBack() + "-" + tmp;

            ViewBag.Price = price;
            ViewBag.Customer = cus;
            ViewBag.CusProList = cusProList;
            return View();
        }

        /// <summary>
        /// 再次下单[提交数据]
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AgainOrder(FormCollection fc)
        {
            //获取订单信息
            Guid cID = new Guid(fc["CustomerID"]);
            Guid tmpID = Guid.NewGuid();
            Customer cus = _customerApp.GetInfo(cID); 
            Order newOrder = new Order();

            List<OrderProduct> newOPList = new List<OrderProduct>();

            //新订单
            newOrder.Id = Guid.NewGuid();
            newOrder.CustomeId = cID;
            newOrder.Channel = fc["Channel"];
            newOrder.Number = fc["Number"];
            newOrder.CusNumber = fc["CusNumber"];
            newOrder.Delivery = fc["Delivery"];
            newOrder.Memo = fc["Memo"];
            newOrder.SendTime = fc["SendTime"];
            newOrder.IsWork = Convert.ToInt32(fc["IsWork"]);
            //newOrder.FinalPrice = order.InitPrice = Convert.ToDecimal(fc["Price"]);
            newOrder.Status = 8; //分配订单
            newOrder.Stage = 3;
            newOrder.SubmitTime = DateTime.Now;
            newOrder.CreateTime = DateTime.Now;
            newOrder.CreatorId = newOrder.UserId = operatorModel.UserId;
            newOrder.CreatorName = operatorModel.FamilyName;

            _orderApp.Insert(newOrder);

            //更新OrderProduct数据
            string proList = fc["ProData"];
            JavaScriptSerializer js = new JavaScriptSerializer();
            List<ProTemp> ls = js.Deserialize<List<ProTemp>>(proList);

            //循环产品数据
            for (int i = 0; i < ls.Count; i++)
            {
                tmpID = Guid.NewGuid(); //采购ID
                if (ls[i].Amount > 0)
                {
                    //更新订货数量
                    OrderProduct oldOP = _orderProductApp.GetSingleOrderProduct(ls[i].OPID);
                    OrderProduct op = new OrderProduct();
                    op.Id = Guid.NewGuid();
                    if (oldOP.PrimaryID != null)
                    {
                        op.PrimaryID = oldOP.PrimaryID;
                    }
                    else
                    {
                        op.PrimaryID = oldOP.Id;
                    }
                    op.Amount = ls[i].Amount;
                    op.PurchaseId = tmpID;
                    op.CostPrice = oldOP.CostPrice;
                    op.FinalPrice = oldOP.FinalPrice;
                    op.OrderId = newOrder.Id;
                    op.Price = oldOP.Price;
                    op.ProductId = oldOP.ProductId;
                    op.WorksheetId = new Guid();
                    op.PriceTime = DateTime.Now;
                    newOPList.Add(op);

                    //插入“生产分配”数据
                    if (newOrder.IsWork == 1)
                    {
                        Purchase pur = new Purchase();
                        pur.Id = tmpID;
                        pur.Status = 1;
                        pur.Type = 1;
                        pur.Amount = ls[i].Amount;
                        pur.ApplyTime = DateTime.Now;
                        pur.ApplyId = operatorModel.UserId;
                        _purchaseApp.Add(pur);
                    }

                    //插入“转库存”申请
                    else if (newOrder.IsWork == 2)
                    {
                        InventoryChangeApply ica = new InventoryChangeApply();
                        ica.Id = Guid.NewGuid();
                        ica.OrderId = newOrder.Id;
                        ica.ProductId = oldOP.ProductId;
                        ica.ApplyAmount = ls[i].Amount;
                        ica.FinishAmount = 0;
                        ica.Status = -1;
                        ica.ApplyTime = DateTime.Now;
                        _inventoryChangeApplyApp.Add(ica);
                    }

                }
            }
            _orderProductApp.Add(newOPList);

            return RedirectToAction("OrderList", "Order");
        }

        /// <summary>
        /// 售后下单
        /// </summary>
        /// <returns></returns>
        public ActionResult SubmitOrder()
        {
            Guid cID = new Guid();
            Customer cus = new Customer();
            User user = new User();
            string str = Request.QueryString["CID"];
            decimal price = 0;

            List<ProductView> cusProList = new List<ProductView>();
            if (str != null)
            {
                cID = new Guid(str);
                cus = _customerApp.GetInfo(cID);
                cusProList = _customerProductApp.GetCustomerOrderProductList(cID);
               user = _userApp.GetForm(cus.UserId);
            }

            DateTime start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            DateTime end = DateTime.Now.AddDays(1);
            int count = _orderApp.GetOrderCount(operatorModel.UserId, start, end);
            count += 1;
            string tmp = count.ToString();
            if (count < 10)
            {
                tmp = "00" + count;
            }
            else if (count < 100)
            {
                tmp = "0" + count;
            }

            ViewBag.Number = user.ShortName.Trim() + "-" + GenerateId.GenerateOrderNumberBack() + "-" + tmp;

            ViewBag.Price = price;
            ViewBag.Customer = cus;
            ViewBag.CusProList = cusProList;
            return View();
        }

        /// <summary>
        /// 售后下单[提交数据]
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SubmitOrder(FormCollection fc)
        {
            //获取订单信息
            Guid cID = new Guid(fc["CustomerID"]);
            Guid tmpID = Guid.NewGuid();
            Customer cus = _customerApp.GetInfo(cID);
            Order newOrder = new Order();

            List<OrderProduct> newOPList = new List<OrderProduct>();

            //新订单
            newOrder.Id = Guid.NewGuid();
            newOrder.CustomeId = cID;
            newOrder.Channel = fc["Channel"];
            newOrder.Number = fc["Number"];
            newOrder.CusNumber = fc["CusNumber"];
            newOrder.Delivery = fc["Delivery"];
            newOrder.Memo = fc["Memo"];
            newOrder.SendTime = fc["SendTime"];
            newOrder.IsWork = Convert.ToInt32(fc["IsWork"]);
            //newOrder.FinalPrice = order.InitPrice = Convert.ToDecimal(fc["Price"]);
            newOrder.Status = 8; //分配订单
            newOrder.Stage = 3;
            newOrder.SubmitTime = DateTime.Now;
            newOrder.CreateTime = DateTime.Now;
            newOrder.UserId = cus.UserId;
            newOrder.CreatorId =  operatorModel.UserId;
            newOrder.CreatorName = operatorModel.FamilyName;

            _orderApp.Insert(newOrder);

            //更新OrderProduct数据
            string proList = fc["ProData"];
            JavaScriptSerializer js = new JavaScriptSerializer();
            List<ProTemp> ls = js.Deserialize<List<ProTemp>>(proList);

            //循环产品列表
            for (int i = 0; i < ls.Count; i++)
            {
                tmpID = Guid.NewGuid(); //采购ID
                if (ls[i].Amount > 0)
                {
                    //更新订货数量
                    OrderProduct oldOP = _orderProductApp.GetSingleOrderProduct(ls[i].OPID);
                    OrderProduct op = new OrderProduct();
                    op.Id = Guid.NewGuid();
                    if (oldOP.PrimaryID != null)
                    {
                        op.PrimaryID = oldOP.PrimaryID;
                    }
                    else
                    {
                        op.PrimaryID = oldOP.Id;
                    }
                    op.Amount = ls[i].Amount;
                    op.PurchaseId = tmpID;
                    op.CostPrice = oldOP.CostPrice;
                    op.FinalPrice = oldOP.FinalPrice;
                    op.OrderId = newOrder.Id;
                    op.Price = oldOP.Price;
                    op.ProductId = oldOP.ProductId;
                    op.WorksheetId = new Guid();
                    op.PriceTime = DateTime.Now;
                    newOPList.Add(op);

                    //插入“生产分配”数据
                    if (newOrder.IsWork == 1)
                    {
                        Purchase pur = new Purchase();
                        pur.Id = tmpID;
                        pur.Status = 1;
                        pur.Type = 1;
                        pur.Amount = ls[i].Amount;
                        pur.ApplyTime = DateTime.Now;
                        pur.ApplyId = operatorModel.UserId;
                        _purchaseApp.Add(pur);
                    }

                    //插入“转库存”申请
                    else if (newOrder.IsWork == 2)
                    {
                        InventoryChangeApply ica = new InventoryChangeApply();
                        ica.Id = Guid.NewGuid();
                        ica.OrderId = newOrder.Id;
                        ica.ProductId = oldOP.ProductId;
                        ica.ApplyAmount= ls[i].Amount;
                        ica.FinishAmount = 0;
                        ica.Status = -1;
                        ica.ApplyTime = DateTime.Now;
                        _inventoryChangeApplyApp.Add(ica);
                    }
                }
            }
            _orderProductApp.Add(newOPList);

            return RedirectToAction("Orders", "CustomerService");
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <returns></returns>
        public ActionResult CancelOrder()
        {
            string str = Request.QueryString["OID"];
            OrderInfo order = new OrderInfo();
            List<ProductView> opList = new List<ProductView>();
            if (str != null)
            {
                Guid oID = new Guid(str);
                order = _orderApp.GetFullInfo(oID);
                if (order != null)
                {
                    opList = _orderProductApp.GetListByOrderID(oID).ToList();
                }
            }

            ViewBag.Order = order;
            ViewBag.OpList = opList;
            return View();
        }


        /// <summary>
        /// 取消订单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CancelOrder(FormCollection fc)
        {
            Guid oID = new Guid(fc["OID"]);
            Order order = _orderApp.GetInfo(oID);
            List<OrderProduct> opList = new List<OrderProduct>();

            if (order != null)
            {
                opList = _orderProductApp.GetList(oID).ToList();
                foreach (var item in opList)
                {
                    item.Status = -1;
                    _orderProductApp.Update(item);
                }
            }

            order.Stage = -10;
            order.Memo = fc["Memo"];
            order.EndTime = DateTime.Now;
            _orderApp.Update(order);
            return RedirectToAction("CancelList", "Order");
        }

        /// <summary>
        /// 完成订单
        /// </summary>
        /// <returns></returns>
        public ActionResult FinishOrder()
        {
            string str = Request.QueryString["OID"];
            OrderInfo order = new OrderInfo();
            List<ProductView> opList = new List<ProductView>();
            if (str != null)
            {
                Guid oID = new Guid(str);
                order = _orderApp.GetFullInfo(oID);
                if (order != null)
                {
                    opList = _orderProductApp.GetListByOrderID(oID).ToList();
                }
            }

            ViewBag.Order = order;
            ViewBag.OpList = opList;
            return View();
        }


        /// <summary>
        /// 完成订单{提交数据}
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult FinishOrder(FormCollection fc)
        {
            Guid oID = new Guid(fc["OID"]);
            Order order = _orderApp.GetInfo(oID);

            order.Stage = 10;
            order.Memo = fc["Memo"];
            order.EndTime = DateTime.Now;
            _orderApp.Update(order);
            return RedirectToAction("FinishList", "Order");
        }

        /// <summary>
        /// 查询已取消订单列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="name"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        public ActionResult CancelList(int page = 1, string start = "", string end = "", string name = "", string number = "")
        {
            DateTime _start = Convert.ToDateTime("2017-1-1"); 
            DateTime _end = DateTime.Now.AddDays(1);
            if (start != "")
            {
                _start = Convert.ToDateTime(start);
            }
            if (end != "")
            {
                _end = Convert.ToDateTime(end);
            }

            ViewBag.Start = _start.ToString("yyyy-MM-dd");
            ViewBag.End = _end.ToString("yyyy-MM-dd");
            ViewBag.Name = name;
            ViewBag.Number = number;

            IPagedList<OrderInfo> orderList = _orderApp.GetList(_start, _end, -10, 0, name, "", number).ToPagedList(page, 10);
            return View(orderList);
        }

        /// <summary>
        /// 查询已完成订单列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="name"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        public ActionResult FinishList(int page = 1, string start = "", string end = "", string name = "", string number = "")
        {
            DateTime _start = Convert.ToDateTime("2017-1-1");
            DateTime _end = DateTime.Now.AddDays(1);
            if (start != "")
            {
                _start = Convert.ToDateTime(start);
            }
            if (end != "")
            {
                _end = Convert.ToDateTime(end);
            }

            ViewBag.Start = _start.ToString("yyyy-MM-dd");
            ViewBag.End = _end.ToString("yyyy-MM-dd");
            ViewBag.Name = name;
            ViewBag.Number = number;

            IPagedList<OrderInfo> orderList = _orderApp.GetList(_start, _end, 10, 0, name, "", number).ToPagedList(page, 10);
            return View(orderList);
        }


        #region 发货单

        public ActionResult InvoiceQuery(int page = 1, string number = "", string takeCompany = "")
        {
            ViewBag.Number = number.Trim();
            ViewBag.TakeCompany = takeCompany.Trim();

            IPagedList<Invoice> tecjList = _invoiceApp.GetInvoiceList(number.Trim(), takeCompany.Trim()).ToPagedList(page, 10);
            return View(tecjList);
        }

        public ActionResult InvoiceQueryInfo(Guid inId)
        {
            Invoice invoice = _invoiceApp.GetSingleInvoice(inId);
            Order order = _orderApp.GetInfo(invoice.OrderId);
            Customer customer = _customerApp.GetInfo(order.CustomeId.Value);
            SendCar sc = _invoiceApp.GetSingleSendCar(invoice.Id);
            ExpressOrder exp = _invoiceApp.GetSingleExpressOrder(invoice.Id);
            ViewBag.SendCar = sc;
            ViewBag.ExpressOrder = exp;
            ViewBag.CustomerShortName = customer.ShortName;
            ViewBag.Invoice = invoice;
            return View(order);
        }

        public ActionResult InvoiceCheck()
        {
            Guid orderId = new Guid(Request.QueryString["OID"]);
            Order order = _orderApp.GetInfo(orderId);
            Customer customer = _customerApp.GetInfo(order.CustomeId.Value);
            User xiaoshou = _customerApp.GetUser(order.UserId.Value);
            List<ProductTechnologyView> proListBack = new List<ProductTechnologyView>();
            List<Guid> guid = new List<Guid>();
            List<ProductTechnologyView> proList = _productApp.GetProductListByOrderId(order.Id).ToList();
            foreach (var item in proList)
            {
                if (guid.Contains(item.ProductId))
                {
                    var obj = proListBack.FirstOrDefault(a => a.ProductId == item.ProductId);
                    if (obj != null)
                    {
                        obj.Amount = obj.Amount + item.Amount;
                    }
                }
                else
                {
                    proListBack.Add(item);
                    guid.Add(item.ProductId);
                }
            }
            foreach (var item in proListBack)
            {
                InventoryUer inv = _inventoryUerApp.GetInventoryByOrder(item.OrderId, item.ProductId);
                decimal amount = 0;
                if (inv != null)
                {
                    amount = inv.Amount;
                }
                item.StorageAmount = amount;
            }
            IEnumerable<InvoceType> invoceTypelist = _invoiceApp.GetInvoceTypeList();
            ViewBag.InvoceTypeList = invoceTypelist;
            ViewBag.ProList = proListBack;
            ViewBag.Customer = customer;
            #region 生成订单号

            string shortName = xiaoshou.ShortName.Trim();
            string shortTime = GenerateId.GenerateyyyyMm();
            Invoice lastCompose = _createNewNumberApp.GetLastInvoiceCheck(shortName + "-" + shortTime);
            int lastNum = 1;
            if (lastCompose != null && lastCompose.Number.Split('-').Length == 3 && Validate.IsIntByParse(lastCompose.Number.Split('-')[2]))
            {
                lastNum = Convert.ToInt32(lastCompose.Number.Split('-')[2]) + 1;
            }
            string newNumber = shortName + "-" + GenerateId.GenerateOrderNumberBack() + "-" + lastNum.ToString().PadLeft(3, '0');//生成采购编号
            #endregion
            ViewBag.GenerateNum = newNumber;//生成发货单号
            ViewBag.OperationName = operatorModel.FamilyName;//操作人
            ViewBag.OperationTime = DateTime.Now.ToString("yyyy-MM-dd");//操作时间
            return View(order);
        }

        /// <summary>
        /// 打印发货单
        /// </summary>
        /// <returns></returns>
        public ActionResult InvoicePrint(Guid inId)
        {
            Invoice invoice = _invoiceApp.GetSingleInvoice(inId);
            Order order = _orderApp.GetInfo(invoice.OrderId);
            Customer customer = _customerApp.GetInfo(order.CustomeId.Value);
            SendCar sc = _invoiceApp.GetSingleSendCar(invoice.Id);
            ExpressOrder exp = _invoiceApp.GetSingleExpressOrder(invoice.Id);
            ViewBag.SendCar = sc;
            ViewBag.ExpressOrder = exp;
            ViewBag.CustomerShortName = customer.ShortName;
            ViewBag.Invoice = invoice;
            ViewBag.Order = order;
            ViewBag.UserName = operatorModel.FamilyName;
            return View(order);
        }


        [HttpPost]
        [HandlerAjaxOnly]
        public string AddInvoice(Invoice web, ExpressOrder exp, SendCar sc, int type)
        {
            DateTime nowTime = DateTime.Now;
            Guid newId = Guid.NewGuid();
            //派车
            if (type == 1)
            {
                sc.InvoicId = newId;
                sc.Id = Guid.NewGuid();
                sc.CreateTime = nowTime;
                sc.Type = 0;
                sc.SendType = 0;
                sc.CreatorId = operatorModel.UserId;
                sc.CreatorName = operatorModel.FamilyName;
                _invoiceApp.AddSendCar(sc);
            }
            //快递
            if (type == 2)
            {
                exp.InvoicId = newId;
                exp.Id = Guid.NewGuid();
                exp.CreateTime = nowTime;
                exp.CreatorId = operatorModel.UserId;
                exp.CreatorName = operatorModel.FamilyName;
                _invoiceApp.AddExpressOrder(exp);
            }
            web.Id = newId;
            web.Status = -1;
            web.CreatorId = operatorModel.UserId;
            web.CreatorName = operatorModel.FamilyName;
            web.CreateTime = nowTime;
            web.ApplyTime = nowTime;
            web.DataBack = web.Data;
            if (web.ReceivedTime < DateTime.Parse("1990-01-01 10:10")) //DateTime.MinValue;
            {
                web.ReceivedTime = DateTime.Now;
            }
            web.ApplyId = operatorModel.UserId;
            web.Type = type;

            _invoiceApp.Add(web);//添加发货单
            Order order = _orderApp.GetInfo(web.OrderId);
            if (order != null && order.Stage == 3)
            {
                _operateRecordApp.UpdateOrderStateById(web.OrderId, 11);//更改订单Status=11:首次已发货
            }

            if (web.Data != null)
            {
                List<DeliveryProduct> proList = Common.Json.ToObject<List<DeliveryProduct>>(web.Data);
                if (proList != null)
                {
                    foreach (var item in proList)
                    {
                        if (item.ProductAmount > 0)
                        {
                            item.Id = Guid.NewGuid();
                            item.InvoiceId = web.Id;
                            _invoiceApp.AddDeliveryProduct(item);//插入发货单对应产品

                            StorageTable e = new StorageTable();//插入库房表
                            Guid newSTid = Guid.NewGuid();
                            e.Id = newSTid;
                            //e.Status = -1;
                            e.Type = 1;
                            //TODO
                            //e.OrderId = web.OrderId;
                            e.ProductId = item.ProductId;
                            //e.Format = item.ProductFormat;
                            //e.Unit = item.ProductUnit;
                            e.Amount = item.ProductAmount;
                            //e.InvoiceID = web.Id;
                            //e.ApplyTime = nowTime;
                            //e.CreatorId = null;
                            //e.CreateTime = null;
                            //e.ApplyId = operatorModel.UserId;
                            _storageTableApp.Add(e);

                            //插入给下一个工作人员添加人工记录
                            OperateRecord o1 = new OperateRecord();
                            o1.Id = Guid.NewGuid();
                            o1.ItemId = newSTid;
                            o1.TypeId = 22;
                            o1.StartTime = nowTime;
                            o1.EndTime = null;
                            o1.CreatorId = null;
                            _operateRecordApp.AddOperateRecord(o1);
                        }
                    }
                }
            }
            return Result.ToJson();
        }

        /// <summary>
        /// 查库存
        /// </summary>
        /// <returns></returns>
        public JsonResult ShowInventory(string oid, string pid)
        {
            Guid orderID = new Guid(oid);
            Guid productID = new Guid(pid);
            InventoryUer inv = _inventoryUerApp.GetInventoryByOrder(orderID, productID);
            decimal amount = 0;
            if (inv != null)
            {
                amount = inv.Amount;
            }
            return Json(amount);
        }

        #endregion
    }

    /// <summary>
    /// json产品数据
    /// </summary>
    public class ProTemp
    {
        public Guid OPID { get; set; }
        public Guid ProductID { get; set; }
        public decimal Amount { get; set; }
    }
}